package com.util;

import android.util.Base64;

/**
 * Created by Mars on 2017/9/26.
 */

public class DataTypeUtil {

    public static byte[] short2byte(short i) {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (0xff & i);
        bytes[1] = (byte) ((0xff00 & i) >> 8);
        return bytes;
    }

    /**
     * byte数组中取int数值，本方法适用于(低位在前，高位在后)的顺序。
     *
     * @param ary    byte数组
     * @param offset 从数组的第offset位开始
     * @return int数值
     */
    public static int bytesToInt(byte[] ary, int offset) {
        int value;
        value = (ary[offset] & 0xFF)
                | ((ary[offset + 1] << 8) & 0xFF00)
                | ((ary[offset + 2] << 16) & 0xFF0000)
                | ((ary[offset + 3] << 24) & 0xFF000000);
        return value;
    }

    /**
     * byte 转 int
     *
     * @param b
     * @return
     */
    public static int byteToInt(byte b) {
        //Java 总是把 byte 当做有符处理；我们可以通过将其和 0xFF 进行二进制与得到它的无符值
        return b & 0xFF;
    }

    public static short byte2short(byte[] b) {
        return (short) (((b[1] << 8) | b[0] & 0xff));
    }

    public static String encoder(String str) {
        byte[] encode = Base64.encode(str.getBytes(), Base64.NO_WRAP);
        String s = new String(encode);
        return s;
    }

    public static String getString(byte[] body) {
        byte[] decode = Base64.decode(body, Base64.DEFAULT);
        String s = new String(decode);
        return s;
    }


}
